<?php
/**
 * 添加会员
 * Created by PhpStorm.
 * User: eric
 * Date: 2020/7/22
 * Time: 12:16
 */

namespace App\Admin\Extensions\Action;

use App\Models\CropsCfg;
use App\Models\FarmOrderPick;
use App\Models\Order;
use App\Models\RefundOrder;
use Encore\Admin\Actions\RowAction;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;

class OrderRefundUpdate extends RowAction
{

    public $name = '处理';

    protected $selector = '.update-refund-order';

    public function handle(Model $model, Request $request)
    {
        //处理逻辑
        $channel = $request->input('channel');
        if (empty($channel)) {
            return $this->response()->error('请填写处理方式');
        }
        try {
            DB::beginTransaction();
            $rel = RefundOrder::where('order_id', $model->id)->where('status', 3)->update(['status' => 2, 'refund_at' => time(), 'channel' => $channel, 'fail_reason' => '']);
            if (!$rel) {
                throw new \Exception('订单退款失败');
            }
            //处理库存
            CropsCfg::where('id', $model->crops_id)->increment('total', $model->total_num);
            CropsCfg::where('id', $model->crops_id)->decrement('surplus', $model->total_num);
            $model->refund_status = 2;
            $model->save();
            DB::commit();
            return $this->response()->success('退款成功')->refresh();
        } catch (\Exception $exception) {
            DB::rollBack();
            return $this->response()->error($exception->getMessage());
        }
    }

    public function form()
    {
        $this->text('channel', '处理方式')->attribute(['autocomplete' => 'off'])->help('例：已打款到用户支付宝账号：xxx@qq.com');
    }
}
